<template>
  <div class="app-container">
    <el-row :gutter="20">
      <!--部门数据-->
      <el-col :span="4" :xs="24">
        <div class="head-container">
          <el-input
            v-model="deptName"
            placeholder="请输入部门名称"
            clearable
            size="small"
            prefix-icon="el-icon-search"
            style="margin-bottom: 20px"
          />
        </div>
        <div class="head-container">
          <el-tree
            :data="deptOptions"
            :props="defaultProps"
            :expand-on-click-node="false"
            :filter-node-method="filterNode"
            ref="tree"
            default-expand-all
            @node-click="handleNodeClick"
          />
        </div>
      </el-col>
      <!--用户数据-->
      <el-col :span="20" :xs="24">
    <el-form :model="queryParams" ref="queryForm" :inline="true" v-show="showSearch" label-width="68px">
      <el-form-item label="名称" prop="name">
        <el-input
          v-model="queryParams.name"
          placeholder="请输入名称"
          clearable
          size="small"
          @keyup.enter.native="handleQuery"
        />
      </el-form-item>
      <el-form-item label="油罐类型" prop="typeId">
        <el-select v-model="queryParams.typeId" placeholder="请选择油罐类型" clearable size="small">
          <el-option
            v-for="dict in typeIdOptions"
            :key="dict.dictValue"
            :label="dict.dictLabel"
            :value="dict.dictValue"
          />
        </el-select>
      </el-form-item>
<!--      <el-form-item label="部门" prop="deptId" v-if="checkRole(['admin'])" >-->
<!--        <treeselect-->
<!--          v-model="queryParams.deptId"-->
<!--          :options="deptOptions"-->
<!--          :show-count="true"-->
<!--          placeholder="请选择归属部门"-->
<!--          style="width: 200px;"-->
<!--        />-->
<!--      </el-form-item>-->

      <el-form-item>
        <el-button type="primary" icon="el-icon-search" size="mini" @click="handleQuery">搜索</el-button>
        <el-button icon="el-icon-refresh" size="mini" @click="resetQuery">重置</el-button>
      </el-form-item>
    </el-form>
        <el-row :gutter="10" class="mb8">
          <el-col :span="1.5">
            <el-button
              type="primary"
              plain
              icon="el-icon-plus"
              size="mini"
              @click="handleAdd"
              v-hasPermi="['oiltank:tank:add']"
            >新增
            </el-button>
          </el-col>
          <el-col :span="1.5">
            <el-button
              type="success"
              plain
              icon="el-icon-edit"
              size="mini"
              :disabled="single"
              @click="handleUpdate"
              v-hasPermi="['oiltank:tank:edit']"
            >修改
            </el-button>
          </el-col>
          <el-col :span="1.5">
            <el-button
              type="danger"
              plain
              icon="el-icon-delete"
              size="mini"
              :disabled="multiple"
              @click="handleDelete"
              v-hasPermi="['oiltank:tank:remove']"
            >删除
            </el-button>
          </el-col>
          <el-col :span="1.5">
            <el-button
              type="warning"
              plain
              icon="el-icon-download"
              size="mini"
              :loading="exportLoading"
              @click="handleExport"
              v-hasPermi="['oiltank:tank:export']"
            >导出
            </el-button>
          </el-col>

          <el-col :span="1.5">
            <el-button
              type="warning"
              plain
              icon="el-icon-s-marketing"
              size="mini"
              @click="handleReport"
              v-hasPermi="['oiltank:tank:export']"
            >储罐信息报表</el-button>
          </el-col>
          <el-col :span="1.5">
            <el-button
              type="warning"
              plain
              icon="el-icon-s-marketing"
              size="mini"
              @click="handleReport1"
              v-hasPermi="['oiltank:tank:export']"
            >每日运销报表</el-button>
          </el-col>

          <el-col :span="1.5">
            <el-button
              type="warning"
              plain
              icon="el-icon-s-marketing"
              size="mini"
              @click="handleReport2"
              v-hasPermi="['oiltank:tank:export']"
            >近七天加油量报表</el-button>
          </el-col>
          <right-toolbar :showSearch.sync="showSearch" @queryTable="getList"></right-toolbar>
        </el-row>

        <el-table
          v-loading="loading"
          :data="tankList"
          @selection-change="handleSelectionChange"
          :row-class-name="tableRowClassName">
          <el-table-column type="selection" width="55" align="center" />
          <el-table-column label="序号" type="index" width="50" align="center">
            <template slot-scope="scope">
              <span>{{(queryParams.pageNum - 1) * queryParams.pageSize + scope.$index + 1}}</span>
            </template>
          </el-table-column>
          <el-table-column label="名称" align="center" prop="name" />
          <el-table-column label="油罐类型" align="center" prop="typeId" :formatter="typeIdFormat" />
          <el-table-column label="最大装油量" align="center" prop="maxCap" />
          <el-table-column label="最小装油量" align="center" prop="minCap" />
          <el-table-column label="油罐状态" align="center" prop="status" :formatter="statusFormat" />
          <el-table-column label="油高(米)" align="center" prop="height" />
          <el-table-column label="安全高度" align="center" prop="safeHeight" />
          <el-table-column label="预警高度" align="center" prop="extra1" />
          <el-table-column label="报警高度" align="center" prop="extra2" />
          <el-table-column label="部门" align="center" prop="deptId" :formatter="deptIdFormat" />
          <el-table-column label="库存(吨)" align="center" prop="weight" />
          <el-table-column label="操作" align="center" class-name="small-padding fixed-width">
            <template slot-scope="scope">
              <el-button
                size="mini"
                type="text"
                icon="el-icon-edit"
                @click="handleUpdate(scope.row)"
                v-hasPermi="['oiltank:tank:edit']"
              >修改</el-button>
              <el-button
                size="mini"
                type="text"
                icon="el-icon-delete"
                @click="handleDelete(scope.row)"
                v-hasPermi="['oiltank:tank:remove']"
              >删除</el-button>
            </template>
          </el-table-column>
        </el-table>


        <pagination
          v-show="total>0"
          :total="total"
          :page.sync="queryParams.pageNum"
          :limit.sync="queryParams.pageSize"
          @pagination="getList"
        />
      </el-col>
    </el-row>


    <!-- 添加或修改储油罐信息对话框 -->
    <el-dialog :title="title" :visible.sync="open" width="600px" append-to-body>
      <el-form ref="form" :model="form" :rules="rules" label-width="180px">

        <el-row :gutter="20">
          <el-col :span="10">

          </el-col>
          <el-col :span="10">

          </el-col>
        </el-row>

        <el-form-item label="油罐名称" prop="name">
          <el-input v-model="form.name" placeholder="请输入油罐名称" style="width: 200px"/>
        </el-form-item>

        <el-form-item label="油罐类型" prop="typeId">
          <el-select v-model="form.typeId" placeholder="请选择油罐类型" style="width: 200px">
            <el-option
              v-for="dict in typeIdOptions"
              :key="dict.dictValue"
              :label="dict.dictLabel"
              :value="parseInt(dict.dictValue)"
            ></el-option>
          </el-select>
        </el-form-item>

        <el-form-item label="最大存油量(吨)" prop="maxCap" v-if="(form.typeId!=3&&form.typeId!=4)">
          <el-input-number :min="0" :precision="4" style="width: 200px" v-model="form.maxCap" placeholder="请输入最大存油量"/>
        </el-form-item>

        <el-form-item label="底油重量(吨)" prop="minCap" v-if="(form.typeId!=3&&form.typeId!=4)">
          <el-input-number :min="0" :precision="4" style="width: 200px" v-model="form.minCap" placeholder="请输入底油重量"/>
        </el-form-item>

        <el-form-item label="油罐状态">
          <el-radio-group v-model="form.status" style="width: 400px">
            <el-radio
              v-for="dict in statusOptions"
              :key="dict.dictValue"
              :label="parseInt(dict.dictValue)"
            >{{ dict.dictLabel }}
            </el-radio>
          </el-radio-group>
        </el-form-item>

        <el-form-item label="油高(米)" prop="height">
          <el-input-number style="width: 200px" :min="0" :precision="4" v-model="form.height" placeholder="请输入油罐高度"/>
        </el-form-item>

        <el-form-item label="库存(吨)" prop="weight" v-if="(form.typeId!=3&&form.typeId!=4)">
          <el-input-number style="width: 200px" :min="0" :precision="4" v-model="form.weight" placeholder="请输入库存(吨)"/>
        </el-form-item>

        <el-form-item label="安全高度(米)" prop="safeHeight" >
          <el-input-number style="width: 200px" :min="0" :precision="4" v-model="form.safeHeight" placeholder="请输入安全高度"/>
        </el-form-item>

        <el-form-item label="预警高度(米)" prop="extra1" v-if="(form.typeId==3||form.typeId==4)">
          <el-input-number style="width: 200px" :min="0" :precision="4" v-model="form.extra1" placeholder="请输入预警高度"/>
        </el-form-item>

        <el-form-item label="报警高度(米)" prop="extra2" v-if="(form.typeId==3||form.typeId==4)">
          <el-input-number style="width: 200px" :min="0" :precision="4" v-model="form.extra2" placeholder="请输入报警高度"/>
        </el-form-item>

        <el-form-item label="归属部门" prop="deptId" v-if="checkRole(['admin'])">
          <treeselect style="width: 200px" v-model="form.deptId" :options="deptOptions" :show-count="true" placeholder="请选择归属部门"/>
        </el-form-item>

      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button type="primary" @click="submitForm">确 定</el-button>
        <el-button @click="cancel">取 消</el-button>
      </div>
    </el-dialog>
  </div>
</template>

<script>
import { listTank, getTank, delTank, addTank, updateTank, exportTank } from '@/api/oiltank/tank'
import Treeselect from '@riophae/vue-treeselect'
import { treeselect } from '@/api/system/dept'
import '@riophae/vue-treeselect/dist/vue-treeselect.css'
import { baseApiUrl } from '@/config/sysinfo'
import { checkRole } from '@/utils/permission'

export default {
  name: 'Tank',
  components: { Treeselect },
  data() {
    return {
      allstatusOptions:[],
      // 部门树选项
      deptOptions: undefined,
      // 遮罩层
      loading: true,
      // 导出遮罩层
      exportLoading: false,
      // 选中数组
      ids: [],
      // 非单个禁用
      single: true,
      // 非多个禁用
      multiple: true,
      // 显示搜索条件
      showSearch: true,
      // 总条数
      total: 0,
      // 储油罐信息表格数据
      tankList: [],
      // 弹出层标题
      title: '',
      // 是否显示弹出层
      open: false,
      // 主键字典
      idOptions: [],
      // 名称字典
      nameOptions: [],
      // 油罐类型字典
      typeIdOptions: [],
      // 油罐类型名称字典
      typeNameOptions: [],
      // 最大装油量字典
      maxCapOptions: [],
      // 最小装油量字典
      minCapOptions: [],
      // 油罐状态字典
      statusOptions: [],
      // 库存(吨)字典
      extra1Options: [],
      // 油罐高度字典
      heightOptions: [],
      // 安全高度字典
      safeHeightOptions: [],
      // extra2字典
      extra2Options: [],
      // extra3字典
      extra3Options: [],
      // extra4字典
      extra4Options: [],
      // 部门ID字典
      deptIdOptions: [],
      // 库存(吨)字典
      weightOptions: [],
      // 部门名称
      deptName: undefined,
      defaultProps: {
        children: "children",
        label: "label"
      },
      tempDeptId:null,
      // 查询参数
      queryParams: {
        pageNum: 1,
        pageSize: 10,
        name: null,
        typeId: null,
        deptId: null
      },
      // 表单参数
      form: {},
      // 表单校验
      rules: {
        name: [
          { required: true, message: '名称不能为空', trigger: 'blur' }
        ],
        typeId: [
          { required: true, message: '油罐类型不能为空', trigger: 'change' }
        ],

        maxCap: [
          { required: true, message: '最大装油量不能为空', trigger: 'blur' }
        ],
        minCap: [
          { required: true, message: '最小装油量不能为空', trigger: 'blur' }
        ],
        status: [
          { required: true, message: '油罐状态不能为空', trigger: 'blur' }
        ],
        height: [
          { required: true, message: '油高(米)不能为空', trigger: 'blur' }
        ],
        safeHeight: [
          { required: true, message: '安全高度不能为空', trigger: 'blur' }
        ],
        // deptId: [
        //   { required: true, message: '部门ID不能为空', trigger: 'blur' }
        // ],
        weight: [
          { required: true, message: '库存(吨)不能为空', trigger: 'blur' }
        ]
      }
    }
  },
  created() {
    this.getList()
    this.getTreeselect()
    this.getDicts('${column.dictType}').then(response => {
      this.idOptions = response.data
    })
    this.getDicts('${column.dictType}').then(response => {
      this.nameOptions = response.data
    })
    this.getDicts('oil_tank_type').then(response => {
      this.typeIdOptions = response.data
    })
    this.getDicts('${column.dictType}').then(response => {
      this.typeNameOptions = response.data
    })
    this.getDicts('${column.dictType}').then(response => {
      this.maxCapOptions = response.data
    })
    this.getDicts('${column.dictType}').then(response => {
      this.minCapOptions = response.data
    })
    this.getDicts('oil_tank_status').then(response => {
      this.allstatusOptions=response.data
      this.statusOptions = response.data
    })
    this.getDicts('${column.dictType}').then(response => {
      this.extra1Options = response.data
    })
    this.getDicts('${column.dictType}').then(response => {
      this.heightOptions = response.data
    })
    this.getDicts('${column.dictType}').then(response => {
      this.safeHeightOptions = response.data
    })
    this.getDicts('${column.dictType}').then(response => {
      this.extra2Options = response.data
    })
    this.getDicts('${column.dictType}').then(response => {
      this.extra3Options = response.data
    })
    this.getDicts('${column.dictType}').then(response => {
      this.extra4Options = response.data
    })
    this.getDicts('${column.dictType}').then(response => {
      this.deptIdOptions = response.data
    })
    this.getDicts('${column.dictType}').then(response => {
      this.weightOptions = response.data
    })
  },
  watch: {
    'form.typeId'(newVal, oldVal) {
      let allowedValues = ['4', '5']
      if (newVal == 3||newVal==4) {
        this.form.status = 5
      } else if(newVal == 2){
        allowedValues = ['1', '2', '3', '4' ]
        this.form.status = 1
        this.form.extra1=null
        this.form.extra2=null
      }else{
        allowedValues = [ '5', '3' ,'4']
        this.form.status = 5
        this.form.extra1=null
        this.form.extra2=null
      }
      this.getDicts('oil_tank_status').then(response => {
        this.statusOptions = response.data.filter(item => allowedValues.includes(item.dictValue))

      })

    },



  },

  methods: {
    tableRowClassName({ row }) {
      if (row.typeId === 3||row.typeId === 4) {
        if (row.height > row.extra2) {
          return 'warning-red'; // 高于报警高度，红色
        } else if (row.height > row.extra1) {
          return 'warning-yellow'; // 高于预警高度，黄色
        }
      }
      return '';
    },
    checkRole,
    /** 查询部门下拉树结构 */
    getTreeselect() {
      treeselect().then(response => {
        this.deptOptions = response.data
        // console.log('this.deptOptions:' + JSON.stringify(this.deptOptions))
      })
    },
    /** 查询储油罐信息列表 */
    getList() {
      this.loading = true
      listTank(this.queryParams).then(response => {
        this.tankList = response.rows
        this.total = response.total
        this.loading = false
      })
    },
    // 主键字典翻译
    idFormat(row, column) {
      return this.selectDictLabel(this.idOptions, row.id)
    },
    // 名称字典翻译
    nameFormat(row, column) {
      return this.selectDictLabel(this.nameOptions, row.name)
    },
    // 油罐类型字典翻译
    typeIdFormat(row, column) {
      return this.selectDictLabel(this.typeIdOptions, row.typeId)
    },
    // 油罐类型名称字典翻译
    typeNameFormat(row, column) {
      return this.selectDictLabel(this.typeNameOptions, row.typeName)
    },
    // 最大装油量字典翻译
    maxCapFormat(row, column) {
      return this.selectDictLabel(this.maxCapOptions, row.maxCap)
    },
    // 最小装油量字典翻译
    minCapFormat(row, column) {
      return this.selectDictLabel(this.minCapOptions, row.minCap)
    },
    // 油罐状态字典翻译
    statusFormat(row, column) {
      return this.selectDictLabel(this.allstatusOptions, row.status)
    },
    // 库存(吨)字典翻译
    extra1Format(row, column) {
      return this.selectDictLabel(this.extra1Options, row.extra1)
    },
    // 油罐高度字典翻译
    heightFormat(row, column) {
      return this.selectDictLabel(this.heightOptions, row.height)
    },
    // 安全高度字典翻译
    safeHeightFormat(row, column) {
      return this.selectDictLabel(this.safeHeightOptions, row.safeHeight)
    },
    // extra2字典翻译
    extra2Format(row, column) {
      return this.selectDictLabel(this.extra2Options, row.extra2)
    },
    // extra3字典翻译
    extra3Format(row, column) {
      return this.selectDictLabel(this.extra3Options, row.extra3)
    },
    // extra4字典翻译
    extra4Format(row, column) {
      return this.selectDictLabel(this.extra4Options, row.extra4)
    },

    deptIdFormat(row, column) {
      const dept = this.findDeptById(this.deptOptions, row.deptId);
      if (dept) {
        return dept.label; // or any other property of `dept` that you want to display
      }
      return 'Department Not Found'; // Default value if the department is not found
    },

    findDeptById(deptOptions, deptId) {

      for (let dept of deptOptions) {
        console.log(dept.id)
        console.log(deptId)
        if ((dept.id + "") === deptId+"") {
          return dept;
        }
        if (dept.children && dept.children.length > 0) {
          const foundDept = this.findDeptById(dept.children, deptId);
          if (foundDept) {
            return foundDept;
          }
        }
      }
      return null; // If no matching department is found
    },


    // 库存(吨)字典翻译
    weightFormat(row, column) {
      return this.selectDictLabel(this.weightOptions, row.weight)
    },
    // 取消按钮
    cancel() {
      this.open = false
      this.reset()
    },
    // 表单重置
    reset() {
      this.form = {
        id: null,
        name: null,
        typeId: null,
        typeName: null,
        maxCap: null,
        minCap: null,
        status: 0,
        extra1: null,
        height: null,
        safeHeight: null,
        extra2: null,
        extra3: null,
        extra4: null,
        deptId: null,
        weight: null
      }
      this.resetForm('form')
    },
    /** 搜索按钮操作 */
    handleQuery() {
      this.queryParams.pageNum = 1
      this.getList()
    },
    /** 重置按钮操作 */
    resetQuery() {
      this.resetForm('queryForm')
      this.handleQuery()
    },
    // 多选框选中数据
    handleSelectionChange(selection) {
      this.ids = selection.map(item => item.id)
      this.single = selection.length !== 1
      this.multiple = !selection.length
    },
    /** 新增按钮操作 */
    handleAdd() {
      this.reset()
      this.form.status = 1
      this.form.typeId = 1
      this.open = true
      this.form.deptId =  this.tempDeptId;
      this.title = '添加储油罐信息'
    },
    /** 修改按钮操作 */
    handleUpdate(row) {
      this.reset()
      const id = row.id || this.ids
      getTank(id).then(response => {
        this.form = response.data
        this.open = true
        this.title = '修改储油罐信息'
      })
    },
    /** 提交按钮 */
    submitForm() {
      this.$refs['form'].validate(valid => {
        if (valid) {
          if (this.form.id != null) {
            updateTank(this.form).then(response => {
              this.msgSuccess('修改成功')
              this.open = false
              this.getList()
            })
          } else {
            addTank(this.form).then(response => {
              this.msgSuccess('新增成功')
              this.open = false
              this.getList()
            })
          }
        }
      })
    },
    /** 删除按钮操作 */
    handleDelete(row) {
      const ids = row.id || this.ids
      this.$confirm('是否确认删除储油罐信息编号为"' + ids + '"的数据项?', '警告', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }).then(function() {
        return delTank(ids)
      }).then(() => {
        this.getList()
        this.msgSuccess('删除成功')
      }).catch(() => {
      })
    },

    handleReport(){
      window.open(process.env.VUE_APP_BASE_API + '/jmreport/view/1008523762432811008', '_blank');

    },
    handleReport1(){
      window.open(process.env.VUE_APP_BASE_API + '/jmreport/view/1006722083819429888', '_blank');
    },
    handleReport2(){
      window.open(process.env.VUE_APP_BASE_API + '/jmreport/view/1006344821341233152', '_blank');
    },
    /** 导出按钮操作 */
    handleExport() {

      this.download('oiltank/tank/export', {
        ...this.queryParams
      }, `tank_${new Date().getTime()}.xlsx`)

      // const queryParams = this.queryParams
      // this.$confirm('是否确认导出所有储油罐信息数据项?', '警告', {
      //   confirmButtonText: '确定',
      //   cancelButtonText: '取消',
      //   type: 'warning'
      // }).then(() => {
      //   this.exportLoading = true
      //   return exportTank(queryParams)
      // }).then(response => {
      //   this.download(response.msg)
      //   this.exportLoading = false
      // }).catch(() => {
      // })
    },
    // 筛选节点
    filterNode(value, data) {
      if (!value) return true;
      return data.label.indexOf(value) !== -1;
    },
    // 节点单击事件
    handleNodeClick(data) {
      this.queryParams.deptId = data.id;
      this.tempDeptId=data.id
      this.getList();
    },
  }
}
</script>
<style>
.warning-yellow {
  background-color: yellow;
}

.warning-red {
  background-color: red;
}

</style>
